package mcia_gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.UIManager;

/*
 * ManagerLSViev.java - preview of CL, allows to change scenes and lights immedetely
 *
 * @author MCIA
 */
public final class ManagerLSView extends javax.swing.JFrame {

    private int floorNumber = 1;                                                //which floor we are at
    private int widthL = 100;                                                   //default width of Light
    private int heightL = 30;
    private int widthCL = 90;
    private int heightCL = 20;
    private int percentageLabelW = 38;
    private int percentageLabelH = 26;
    private Color lightsTextColor = new Color(0, 77, 153);                      //lights description colour
    private Color contrastboxBgColor = new Color(255, 255, 255);                //background color of light numbers and brightness
    private Color lightsBorderColor = new Color(51, 204, 255);                  //border color (to see the lights position better)
    private int currentFloor = 1;
    private int currentCL = 0;
    private String currentSceneName = "";                                       //name of current scene
    private String dbName = "mcia";                                             //name of db we are connecting to
    private DatabaseEss db;
    private int loadedAll = 0;                                                  //checking if we loaded initiated settings
    private int loadedCL = 0;
    private final MouseListener listener, listenerLight;
    private static String currentCLName = "CL";                                 //name of current CL
    private String singleLight = "";

    /** Creates new form Interface */
    public ManagerLSView() {
        initComponents();

        //listener for CLs
        listener = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                // opening window for adding CL
                currentCLName = e.getComponent().getName();
                int lastDotPos = currentCLName.lastIndexOf(".");
                currentCLName = currentCLName.substring(lastDotPos + 1, currentCLName.length());

                //setting current CL view
                if (loadedAll == 1) {
                    loadedCL = 1;
                    String currentFloorDescription = floorCombo.getSelectedItem().toString();

                    //getting floor id
                    int floorID = 1;
                    try {
                        db.stmt = db.conn.createStatement();
                        ResultSet results;
                        String query;
                        query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                        results = db.stmt.executeQuery(query);

                        results.next();
                        floorID = results.getInt("FLOOR");

                        results.close();

                        //closing connection
                        db.stmt.close();

                    } catch (SQLException ex) {
                        Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    currentFloor = floorID;

                    //deleting all comps from layeredPane except of imageLabel
                    clearLayeredPane(layeredPane);
                    currentCL = Integer.parseInt(currentCLName);
                    loadedAll = 0;
                    if (clCombo.getSelectedItem().equals("- Whole Floor -")) {
                        loadFromDB(currentFloor, 0, currentSceneName);
                    } else {
                        loadFromDB(currentFloor, currentCL, currentSceneName);
                    }

                    loadedAll = 1;

                    floorCombo.setSelectedItem(currentFloorDescription);
                    clCombo.setSelectedIndex(currentCL);
                    loadedCL = 0;
                }

            }

            public void mousePressed(MouseEvent e) {
                //
            }

            public void mouseReleased(MouseEvent e) {
                //
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //listener for Lights
        listenerLight = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                //opening window for changing single light brightness
                setSingleLightFrame.setVisible(true);
                String lightName = e.getComponent().getName();
                singleLightTitleLabel.setText("Edit Light " + currentFloor + "." + lightName.substring(6) + " Brightness:");
                singleLight = currentFloor + "." + lightName.substring(6);
            }

            public void mousePressed(MouseEvent e) {
                //
            }

            public void mouseReleased(MouseEvent e) {
                //
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //setting position of single light edit window
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension scrnsize = toolkit.getScreenSize();
        setSingleLightFrame.setLocation(scrnsize.width / 2 - (setSingleLightFrame.getWidth() / 2), scrnsize.height / 2 - (setSingleLightFrame.getHeight() / 2));

        //setting name for imageLabel
        imageLabel.setName("map_image");

        //descriptionLabel
        descriptionLabel.setText("");

        //setting text to status label
        statusLabel.setText("User: " + LogOn.globalUsername + " | Floor: " + floorNumber);

        db = new DatabaseEss(dbName);

        loadFromDB(currentFloor, currentCL, currentSceneName);
        loadedAll = 1;

    }

    public ManagerLSView(int floorView, String floorViewDescription, int clView) {
        initComponents();

        //listener for CLs
        listener = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                // opening window for adding CL
                currentCLName = e.getComponent().getName();
                int lastDotPos = currentCLName.lastIndexOf(".");
                currentCLName = currentCLName.substring(lastDotPos + 1, currentCLName.length());
                //setting current CL view
                if (loadedAll == 1) {
                    loadedCL = 1;
                    String currentFloorDescription = floorCombo.getSelectedItem().toString();

                    //getting floor id
                    int floorID = 1;
                    try {
                        db.stmt = db.conn.createStatement();
                        ResultSet results;
                        String query;
                        query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                        results = db.stmt.executeQuery(query);

                        results.next();
                        floorID = results.getInt("FLOOR");

                        results.close();

                        //closing connection
                        db.stmt.close();

                    } catch (SQLException ex) {
                        Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    currentFloor = floorID;

                    //deleting all comps from layeredPane except of imageLabel
                    clearLayeredPane(layeredPane);
                    currentCL = Integer.parseInt(currentCLName);
                    loadedAll = 0;
                    if (clCombo.getSelectedItem().equals("- Whole Floor -")) {
                        loadFromDB(currentFloor, 0, currentSceneName);
                    } else {
                        loadFromDB(currentFloor, currentCL, currentSceneName);
                    }

                    loadedAll = 1;

                    floorCombo.setSelectedItem(currentFloorDescription);
                    //FIXME: do poprawki wybieranie indeksu (poki co jest tylko po numerze indeksu a powinno byc po poprawnej CL)
                    clCombo.setSelectedIndex(currentCL);
                    loadedCL = 0;
                }

            }

            public void mousePressed(MouseEvent e) {
                //
            }

            public void mouseReleased(MouseEvent e) {
                //
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //listener for Lights
        listenerLight = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                //opening window for changing single light brightness
                setSingleLightFrame.setVisible(true);
                String lightName = e.getComponent().getName();
                singleLightTitleLabel.setText("Edit Light " + currentFloor + "." + lightName.substring(6) + " Brightness:");
                singleLight = currentFloor + "." + lightName.substring(6);
            }

            public void mousePressed(MouseEvent e) {
                //
            }

            public void mouseReleased(MouseEvent e) {
                //
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //setting position of single light edit window
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension scrnsize = toolkit.getScreenSize();
        setSingleLightFrame.setLocation(scrnsize.width / 2 - (setSingleLightFrame.getWidth() / 2), scrnsize.height / 2 - (setSingleLightFrame.getHeight() / 2));

        //setting name for imageLabel
        imageLabel.setName("map_image");

        //descriptionLabel
        descriptionLabel.setText("");

        //setting text to status label
        statusLabel.setText("User: " + LogOn.globalUsername + " | Floor: " + floorNumber);

        db = new DatabaseEss(dbName);

        loadFromDB(floorView, clView, currentSceneName);
        loadedAll = 1;

        floorCombo.setSelectedItem(floorViewDescription);
        clCombo.setSelectedIndex(clView);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        setSingleLightFrame = new javax.swing.JFrame();
        jPanel5 = new javax.swing.JPanel();
        singleLightTitleLabel = new javax.swing.JLabel();
        singleLightPercentLabel = new javax.swing.JLabel();
        singleLightSetButton = new javax.swing.JButton();
        singleLightScrollbar = new javax.swing.JScrollBar();
        jPanel1 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        floorCombo = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        clCombo = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        lsCombo = new javax.swing.JComboBox();
        setButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        layeredPane = new javax.swing.JLayeredPane();
        imageLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lightsStatusList = new javax.swing.JList();
        jLabel7 = new javax.swing.JLabel();
        backButton = new javax.swing.JButton();

        setSingleLightFrame.setTitle("Edit Light Brightness");
        setSingleLightFrame.setAlwaysOnTop(true);
        setSingleLightFrame.setMinimumSize(new java.awt.Dimension(395, 190));
        setSingleLightFrame.setResizable(false);

        singleLightTitleLabel.setFont(new java.awt.Font("Tahoma", 0, 14));
        singleLightTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        singleLightTitleLabel.setText("Edit Light Brightness:");

        singleLightPercentLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        singleLightPercentLabel.setText("0%");

        singleLightSetButton.setText("Set");
        singleLightSetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                singleLightSetButtonActionPerformed(evt);
            }
        });

        singleLightScrollbar.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
        singleLightScrollbar.setVisibleAmount(0);
        singleLightScrollbar.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
            public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
                singleLightScrollbarAdjustmentValueChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(singleLightTitleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                                .addComponent(singleLightScrollbar, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(15, 15, 15)
                                .addComponent(singleLightPercentLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addComponent(singleLightSetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(134, 134, 134))))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(singleLightTitleLabel)
                .addGap(18, 18, 18)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(singleLightPercentLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
                    .addComponent(singleLightScrollbar, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(singleLightSetButton, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)
                .addGap(12, 12, 12))
        );

        javax.swing.GroupLayout setSingleLightFrameLayout = new javax.swing.GroupLayout(setSingleLightFrame.getContentPane());
        setSingleLightFrame.getContentPane().setLayout(setSingleLightFrameLayout);
        setSingleLightFrameLayout.setHorizontalGroup(
            setSingleLightFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(setSingleLightFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        setSingleLightFrameLayout.setVerticalGroup(
            setSingleLightFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(setSingleLightFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MCIA LightControl");
        setBounds(new java.awt.Rectangle(200, 20, 800, 600));
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: Manager1 | Current Floor: 1 | Current CL: 1.3");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel2.setPreferredSize(new java.awt.Dimension(800, 72));

        floorCombo.setOpaque(false);
        floorCombo.setPreferredSize(new java.awt.Dimension(60, 20));
        floorCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                floorComboActionPerformed(evt);
            }
        });

        jLabel3.setText("Select Floor:");

        jLabel4.setText("Select CL:");

        clCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- Whole Floor -" }));
        clCombo.setPreferredSize(new java.awt.Dimension(60, 20));
        clCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clComboActionPerformed(evt);
            }
        });

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel8.setText("Local Scene:");

        lsCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                lsComboItemStateChanged(evt);
            }
        });
        lsCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lsComboActionPerformed(evt);
            }
        });

        setButton.setText("Set");
        setButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(floorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(clCombo, 0, 120, Short.MAX_VALUE))
                .addGap(54, 54, 54)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lsCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(setButton, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                .addGap(179, 179, 179))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(floorCombo, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                            .addComponent(clCombo, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(setButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lsCombo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))))
                .addContainerGap())
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        layeredPane.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageLabel.setPreferredSize(new java.awt.Dimension(200, 200));
        imageLabel.setBounds(10, 20, 610, 390);
        layeredPane.add(imageLabel, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPane1.setViewportView(layeredPane);

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Local Scene Changer");

        descriptionLabel.setForeground(new java.awt.Color(51, 102, 255));
        descriptionLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        descriptionLabel.setText("Description Label");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                    .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(descriptionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        lightsStatusList.setEnabled(false);
        jScrollPane2.setViewportView(lightsStatusList);

        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("Lights Status:");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(10, Short.MAX_VALUE))
        );

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 651, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(22, 22, 22))))
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(backButton, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                        .addGap(4, 4, 4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        //we show next screen
        ManagerWelcome floorChooseScreen = new ManagerWelcome();
        Main.changeFrame(floorChooseScreen);
    }//GEN-LAST:event_backButtonActionPerformed

    private void lsComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lsComboActionPerformed
        //load settings for other scene
        if (loadedAll == 1) {

            //getting floor id
            String currentFloorDescription = floorCombo.getSelectedItem().toString();
            int floorID = 1;
            try {
                db.stmt = db.conn.createStatement();
                ResultSet results;
                String query;
                query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                results = db.stmt.executeQuery(query);

                results.next();
                floorID = results.getInt("FLOOR");

                results.close();

                //closing connection
                db.stmt.close();

            } catch (SQLException ex) {
                Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
            }

            currentFloor = floorID;

            int clID = clCombo.getSelectedIndex();

            //deleting all comps from layeredPane except of imageLabel
            clearLayeredPane(layeredPane);

            //getting current scene name
            currentSceneName = lsCombo.getSelectedItem().toString();
            loadedAll = 0;

            //loading all lights for current floor, cl, and scene name
            loadFromDB(currentFloor, currentCL, currentSceneName);
            floorCombo.setSelectedItem(currentFloorDescription);
            clCombo.setSelectedIndex(clID);

            loadedAll = 1;

        }
    }//GEN-LAST:event_lsComboActionPerformed

    private void lsComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_lsComboItemStateChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_lsComboItemStateChanged

    private void floorComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_floorComboActionPerformed
        //filtering CLs for particular floor
        if (loadedAll == 1 && loadedCL == 0) {
            String currentFloorDescription = floorCombo.getSelectedItem().toString();

            //getting floor id
            int floorID = 1;
            try {
                db.stmt = db.conn.createStatement();
                ResultSet results;
                String query;
                query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                results = db.stmt.executeQuery(query);

                results.next();
                floorID = results.getInt("FLOOR");

                results.close();

                //closing connection
                db.stmt.close();

            } catch (SQLException ex) {
                Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
            }
            loadedAll = 0;
            currentFloor = floorID;

            //deleting all comps from layeredPane except of imageLabel
            clearLayeredPane(layeredPane);
            loadFromDB(currentFloor, 0, currentSceneName);
            loadedAll = 1;

            floorCombo.setSelectedItem(currentFloorDescription);
            //FIXME: do poprawki wybieranie indeksu (poki co jest tylko po numerze indeksu a powinno byc po poprawnej CL)
            clCombo.setSelectedIndex(0);
        }
    }//GEN-LAST:event_floorComboActionPerformed

    private void clComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clComboActionPerformed
        //setting current CL view
        if (loadedAll == 1) {
            loadedCL = 1;
            String currentFloorDescription = floorCombo.getSelectedItem().toString();

            //getting floor id
            int floorID = 1;
            try {
                db.stmt = db.conn.createStatement();
                ResultSet results;
                String query;
                query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                results = db.stmt.executeQuery(query);

                results.next();
                floorID = results.getInt("FLOOR");

                results.close();

                //closing connection
                db.stmt.close();

            } catch (SQLException ex) {
                Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
            }
            currentFloor = floorID;
            //deleting all comps from layeredPane except of imageLabel
            clearLayeredPane(layeredPane);

            currentCL = clCombo.getSelectedIndex();
            loadedAll = 0;
            if (clCombo.getSelectedItem().equals("- Whole Floor -")) {
                loadFromDB(currentFloor, 0, currentSceneName);
            } else {
                loadFromDB(currentFloor, currentCL, currentSceneName);
            }

            loadedAll = 1;

            floorCombo.setSelectedItem(currentFloorDescription);
            //FIXME: do poprawki wybieranie indeksu (poki co jest tylko po numerze indeksu a powinno byc po poprawnej CL)
            clCombo.setSelectedIndex(currentCL);
            loadedCL = 0;
        }
    }//GEN-LAST:event_clComboActionPerformed

    private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setButtonActionPerformed
        //setting new values for light's brightness in db
        setNewScene();
    }//GEN-LAST:event_setButtonActionPerformed

    private void singleLightSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_singleLightSetButtonActionPerformed
        try {
            //setting single light brightness
            String bright = singleLightPercentLabel.getText().substring(0, singleLightPercentLabel.getText().length() - 1);
            String floor = singleLight.substring(0, singleLight.indexOf("."));
            String cl = singleLight.substring(singleLight.indexOf(".") + 1, singleLight.lastIndexOf("."));
            String light = singleLight.substring(singleLight.lastIndexOf(".") + 1);

            int newBrightness = Integer.parseInt(bright);
            int thisFloor = Integer.parseInt(floor);
            int thisCL = Integer.parseInt(cl);
            int thisLight = Integer.parseInt(light);

            db.stmt = db.conn.createStatement();
            String query = "UPDATE units SET BRIGHTNESS = " + newBrightness + " WHERE floor = " + thisFloor + " AND cl = " + thisCL + " AND light = " + thisLight + "";
            int results2 = db.stmt.executeUpdate(query);
            if (results2 == 0) {
                System.out.println("Error: Light status not changed!");
            }
            db.stmt.close();

            System.out.println("Light " + singleLight + " updated.");
        } catch (SQLException ex) {
            Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
        }
        setSingleLightFrame.setVisible(false);

        String currentFloorDescription = floorCombo.getSelectedItem().toString();
        ManagerLSView manView = new ManagerLSView(currentFloor, currentFloorDescription, currentCL);
        Main.changeFrame(manView);
}//GEN-LAST:event_singleLightSetButtonActionPerformed

    private void singleLightScrollbarAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_singleLightScrollbarAdjustmentValueChanged
        //setting value to text label
        int value = singleLightScrollbar.getValue();
        singleLightPercentLabel.setText(value + "%");
}//GEN-LAST:event_singleLightScrollbarAdjustmentValueChanged

    public void setNewScene() {
        try {
            //saving new scene lights settings into db
            String nameOfScene = lsCombo.getSelectedItem().toString();
            db.stmt = db.conn.createStatement();
            ResultSet results3 = db.stmt.executeQuery(""
                    + "SELECT lm.*, ls.*, u.FLOOR, u.CL, u.LIGHT, u.DESCRIPTION, u.PX, u.PY, u.BRIGHTNESS as CURRENT_BRIGHTNESS "
                    + "FROM local_memberships lm "
                    + "JOIN local_scenes ls ON (lm.LS_ID = ls.ID) "
                    + "JOIN units u ON (lm.UNIT_FLOOR = u.FLOOR AND lm.UNIT_CL = u.CL AND lm.UNIT_LIGHT = u.LIGHT)"
                    + "WHERE name = '" + nameOfScene + "' AND floor = " + currentFloor + "");
            while (results3.next()) {
                String st1 = results3.getString("FLOOR");
                String st2 = results3.getString("CL");
                String st3 = results3.getString("LIGHT");
                String st4 = results3.getString("BRIGHTNESS");
                //showing brightness percentage in status list

                int newBrightness = Integer.parseInt(st4);
                int thisFloor = Integer.parseInt(st1);
                int thisCL = Integer.parseInt(st2);
                int thisLight = Integer.parseInt(st3);

                db.stmt = db.conn.createStatement();
                String query = "UPDATE units SET BRIGHTNESS = " + newBrightness + " WHERE floor = " + thisFloor + " AND cl = " + thisCL + " AND light = " + thisLight + "";
                int results2 = db.stmt.executeUpdate(query);

                if (results2 == 0) {
                    System.out.println("Error: Light status not changed!");
                }
            }
            results3.close();
        } catch (SQLException ex) {
            Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loadFromDB(int currentFloor, int currentCL, String currentSceneName) {
        //loading lights from database
        floorCombo.removeAllItems();
        lsCombo.removeAllItems();
        clCombo.removeAllItems();
        clCombo.addItem("- Whole Floor -");

        try {
            //loading floors into combo
            db.stmt = db.conn.createStatement();
            ResultSet results0 = db.stmt.executeQuery("SELECT * FROM units");

            while (results0.next()) {
                //adding local scenes to combo
                if (results0.getString("CL").equals("0") && results0.getString("LIGHT").equals("0")) {
                    //adding floor to comboList in right position (sort)
                    String floorName = results0.getString("DESCRIPTION");
                    int howMany = floorCombo.getItemCount();
                    boolean added = false;
                    for (int i = 0; i < howMany; i++) {
                        String obj = floorCombo.getItemAt(i).toString();
                        String stringToCompare = floorName;
                        String stringToCompare2 = obj;
                        int compare = stringToCompare.compareToIgnoreCase(stringToCompare2);
                        int numberLength1 = stringToCompare.indexOf(".");
                        int numberLength2 = stringToCompare2.indexOf(".");
                        if (numberLength1 < numberLength2) {
                            floorCombo.insertItemAt(floorName, i);
                            added = true;
                            break;
                        } else if (compare <= 0 && numberLength1 == numberLength2) {
                            floorCombo.insertItemAt(floorName, i);
                            added = true;
                            break;
                        }
                    }
                    if (added == false) {
                        floorCombo.addItem(floorName);
                    }
                }
                if (results0.getString("FLOOR").equals("" + currentFloor) && !results0.getString("CL").equals("0") && results0.getString("LIGHT").equals("0")) {
                    clCombo.addItem("CL " + results0.getString("FLOOR") + "." + results0.getString("CL"));
                }
            }
            results0.close();

            //adding all lights (even without local scenes) on bottom layer
            db.stmt = db.conn.createStatement();
            ResultSet results_light = db.stmt.executeQuery("SELECT * FROM units "
                    + "WHERE floor = " + currentFloor + " "
                    + "AND CL = " + currentCL + " "
                    + "AND LIGHT <> 0");

            while (results_light.next()) {
                JButton newL = new JButton("" + results_light.getString("FLOOR") + "." + results_light.getString("CL") + "." + results_light.getString("LIGHT"));
                try {
                    newL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bulb.jpg")));
                } catch (Exception ex) {
                    System.out.println("No bulb icon in correct location: " + ex);
                }
                newL.setName("Light " + results_light.getString("CL") + "." + results_light.getString("LIGHT"));
                newL.setBorderPainted(false);
                newL.setContentAreaFilled(false);
                newL.setDefaultCapable(false);
                newL.setHideActionText(true);
                newL.setForeground(lightsTextColor);
                newL.setBounds(results_light.getInt("PX"), results_light.getInt("PY"), widthL, heightL);
                newL.addMouseListener(listenerLight);
                layeredPane.add(newL);

                //showing brightness percentage
                JLabel brightness = new JLabel();
                brightness.setBounds(results_light.getInt("PX") - 13, results_light.getInt("PY") + 2, percentageLabelW, percentageLabelH);

                brightness.setBackground(contrastboxBgColor);
                brightness.setOpaque(true);
                int brightnessValue = Integer.parseInt(results_light.getString("BRIGHTNESS"));
                brightness.setText(brightnessValue + "%");

                //setting colour for brightness representation
                Color off = new Color(0, 38, 77);
                Color on = new Color(0, 128, 255);
                if (brightnessValue <= 50) {
                    brightness.setForeground(off);
                } else {
                    brightness.setForeground(on);
                }

                brightness.setHorizontalAlignment(JLabel.CENTER);
                brightness.setName("brightness_label");
                layeredPane.add(brightness);

                //white field for contras under light description
                JLabel square = new JLabel();
                square.setOpaque(true);
                square.setBackground(contrastboxBgColor);
                square.setBounds(results_light.getInt("PX") + 24, results_light.getInt("PY"), widthL - 19, heightL);
                layeredPane.add(square);

                //border for better visibility
                JLabel colorFrame = new JLabel();
                colorFrame.setBounds(results_light.getInt("PX") - 15, results_light.getInt("PY"), widthL + 20, heightL);
                colorFrame.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, lightsBorderColor));
                layeredPane.add(colorFrame);
                layeredPane.moveToFront(colorFrame);

            }
            results_light.close();
        } catch (SQLException e) {
            System.out.print("Error 3.1 (with loading floors): " + e);
        }

        try {
            //adding lights to panel
            db.stmt = db.conn.createStatement();
            ResultSet results;
            String query;

            query = ""
                    + "SELECT * FROM local_memberships lm "
                    + "JOIN local_scenes ls ON (lm.LS_ID = ls.ID) "
                    + "JOIN units u ON (lm.UNIT_FLOOR = u.FLOOR AND lm.UNIT_CL = u.CL AND lm.UNIT_LIGHT = u.LIGHT)"
                    + "WHERE floor = " + currentFloor + " AND CL = " + currentCL + " AND NAME = '" + currentSceneName + "'";
            results = db.stmt.executeQuery(query);

            ResultSetMetaData rsmd = results.getMetaData();

            while (results.next()) {
                //making new lights with brightness labels
                if (!results.getString("LIGHT").equals("0")) {
                    JButton newL = new JButton("" + results.getString("FLOOR") + "." + results.getString("CL") + "." + results.getString("LIGHT"));
                    try {
                        newL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bulb.jpg")));
                    } catch (Exception ex) {
                        System.out.println("No bulb icon in correct location: " + ex);
                    }
                    newL.setName("Light " + results.getString("CL") + "." + results.getString("LIGHT"));
                    newL.setBorderPainted(false);
                    newL.setContentAreaFilled(false);
                    newL.setDefaultCapable(false);
                    newL.setHideActionText(true);
                    newL.setForeground(lightsTextColor);
                    newL.setBounds(results.getInt("PX"), results.getInt("PY"), widthL, heightL);
                    layeredPane.add(newL);

                    //showing brightness percentage
                    JLabel brightness = new JLabel();
                    brightness.setBounds(results.getInt("PX") - 13, results.getInt("PY") + 2, percentageLabelW, percentageLabelH);

                    brightness.setBackground(contrastboxBgColor);
                    brightness.setOpaque(true);
                    int brightnessValue = Integer.parseInt(results.getString("BRIGHTNESS"));
                    brightness.setText(brightnessValue + "%");

                    //setting colour for brightness representation
                    Color off = new Color(0, 38, 77);
                    Color on = new Color(0, 128, 255);
                    if (brightnessValue <= 50) {
                        brightness.setForeground(off);
                    } else {
                        brightness.setForeground(on);
                    }

                    brightness.setHorizontalAlignment(JLabel.CENTER);
                    brightness.setName("brightness_label");
                    layeredPane.add(brightness);
                    //setting top layer for brightness label
                    layeredPane.moveToFront(brightness);

                    //white field for contrast under light description
                    JLabel square = new JLabel();
                    square.setOpaque(true);
                    square.setBackground(contrastboxBgColor);
                    square.setBounds(results.getInt("PX"), results.getInt("PY"), widthL - 5, heightL);
                    layeredPane.add(square);

                    //setting image to bottom layer (to show up buttons)
                    layeredPane.setLayer(imageLabel, 0);
                }

                //setting image to bottom layer (to show up buttons)
                layeredPane.setLayer(imageLabel, 0);

            }
            results.close();

            //adding CLs into panel
            db.stmt = db.conn.createStatement();
            ResultSet results11 = db.stmt.executeQuery("SELECT * FROM units WHERE floor = " + currentFloor);

            while (results11.next()) {
                //adding CLs to layeredPane
                if (currentCL == 0 && !results11.getString("CL").equals("0") && results11.getString("LIGHT").equals("0")) {
                    JButton newCL = new JButton("CL " + results11.getString("FLOOR") + "." + results11.getString("CL"));
                    newCL.setName("CL " + results11.getString("FLOOR") + "." + results11.getString("CL"));
                    newCL.setBounds(Integer.parseInt(results11.getString("PX")), Integer.parseInt(results11.getString("PY")), widthCL, heightCL);
                    newCL.addMouseListener(listener);
                    layeredPane.add(newCL);
                }
            }
            results11.close();

            //loading scenes into combo
            db.stmt = db.conn.createStatement();
            ResultSet results2 = db.stmt.executeQuery("SELECT * FROM local_scenes");

            lsCombo.setEnabled(true);
            lsCombo.addItem("- Current status -");
            while (results2.next()) {
                //adding local scenes to combo
                String st = results2.getString("NAME");
                String namePrefix = st.substring(0, (st.indexOf(":")));
                String lookFor = "CL " + currentFloor + "." + currentCL;
                if (namePrefix.equals(lookFor)) {
                    lsCombo.addItem(st);
                }
                if (lsCombo.getItemCount() == 0 && currentCL == 0) {
                    lsCombo.addItem("- Select CL First -");
                    lsCombo.setEnabled(false);
                }
            }
            //getting ls name
            String nameOfScene;
            if (currentSceneName.equals("")) {
                nameOfScene = lsCombo.getSelectedItem().toString();
            } else {
                nameOfScene = currentSceneName;
            }
            results2.close();

            //setting current selected scene
            for (int i = 0; i < lsCombo.getItemCount(); i++) {
                if (lsCombo.getItemAt(i).equals(currentSceneName)) {
                    lsCombo.setSelectedIndex(i);
                }
            }

            //loading all lights current status into lights list
            DefaultListModel listModel = new DefaultListModel();
            db.stmt = db.conn.createStatement();
            ResultSet results_light = db.stmt.executeQuery("SELECT * FROM units "
                    + "WHERE floor = " + currentFloor + " "
                    + "AND CL = " + currentCL + " "
                    + "AND LIGHT <> 0");
            while (results_light.next()) {
                String st1 = results_light.getString("FLOOR");
                String st2 = results_light.getString("CL");
                String st3 = results_light.getString("LIGHT");
                String st4 = results_light.getString("BRIGHTNESS");
                //showing brightness percentage in status list
                listModel.addElement(st1 + "." + st2 + "." + st3 + ": " + st4 + "%");
            }
            lightsStatusList.setModel(listModel);
            results_light.close();

            //changing lights status for lights that exist in LocalScene, all other stays as previous
            db.stmt = db.conn.createStatement();
            ResultSet results3 = db.stmt.executeQuery(""
                    + "SELECT lm.*, ls.*, u.FLOOR, u.CL, u.LIGHT, u.DESCRIPTION, u.PX, u.PY, u.BRIGHTNESS as CURRENT_BRIGHTNESS FROM local_memberships lm "
                    + "JOIN local_scenes ls ON (lm.LS_ID = ls.ID) "
                    + "JOIN units u ON (lm.UNIT_FLOOR = u.FLOOR AND lm.UNIT_CL = u.CL AND lm.UNIT_LIGHT = u.LIGHT)"
                    + "WHERE name = '" + nameOfScene + "' AND floor = " + currentFloor + "");

            while (results3.next()) {
                String st1 = results3.getString("FLOOR");
                String st2 = results3.getString("CL");
                String st3 = results3.getString("LIGHT");
                String st4 = results3.getString("BRIGHTNESS");
                //showing brightness percentage in status list
                String lightStatus = st1 + "." + st2 + "." + st3 + ": " + st4 + "%";
                for (int i = 0; i < listModel.getSize(); i++) {
                    int pos = listModel.getElementAt(i).toString().indexOf(":");
                    String lookFor = listModel.getElementAt(i).toString().substring(0, pos);
                    if (lookFor.equals(st1 + "." + st2 + "." + st3)) {
                        listModel.setElementAt(lightStatus, i);
                    }
                }
            }
            lightsStatusList.setModel(listModel);
            results3.close();
        } catch (SQLException e) {
            System.out.println("Error 3.2 (with adding lights or CLs: " + e);
        }

        try {
            //loading floor image
            ResultSet rs = db.stmt.executeQuery(
                    "SELECT image FROM units WHERE floor = " + currentFloor + " AND cl = " + currentCL + " AND light = 0");

            while (rs.next()) {
                Blob blob = rs.getBlob(1);
                int bLength = (int) (blob.length());
                //making image
                byte[] bytesImage = blob.getBytes(1, bLength);
                ImageIcon icon = new ImageIcon(bytesImage);
                imageLabel.setIcon(icon);
                int imgW = icon.getIconWidth();
                int imgH = icon.getIconHeight();
                imageLabel.setBounds(0, 0, imgW, imgH);
                Dimension wymiary = new Dimension(imgW, imgH);
                layeredPane.setPreferredSize(wymiary);
            }
            rs.close();

            //setting image to bottom layer (to show up buttons)
            layeredPane.setLayer(imageLabel, 0);

            //closing connection
            db.stmt.close();
            //db.shutdownDB(dbName);
        } catch (Exception ex) {
            imageLabel.setIcon(null);
            System.out.println("No image for this view: " + ex);
        }
        layeredPane.repaint();

    }

    public void clearLayeredPane(JLayeredPane pane) {
        //deleting all components in layeredPane except of image map
        int howMany = pane.getComponentCount();
        int j = 0;
        while (j < howMany) {
            int i = j;
            int howMany2 = pane.getComponentCount();
            while (i < howMany2) {
                if (pane.getComponent(i).getName() == null || !pane.getComponent(i).getName().equals("map_image")) {
                    pane.remove(i);
                    howMany2 = pane.getComponentCount();
                } else {
                    i++;
                }
            }
            j++;
        }
    }

    public String getFirstLocalScene() {
        //getting first scene for combo
        try {
            db.stmt = db.conn.createStatement();
            ResultSet results;
            String query;
            query = "select * from local_scenes";
            results = db.stmt.executeQuery(query);

            String firstSceneName;
            if (results.next()) {
                firstSceneName = results.getString("NAME");
            } else {
                return "";
            }

            results.close();

            //closing connection
            db.stmt.close();

            return firstSceneName;

        } catch (SQLException ex) {
            Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    //new AdmWelcome().setVisible(true);
                    LogOn thisFrame = new LogOn();
                    String[] vars = null;
                    Main.main(vars);
                    Main.changeFrame(thisFrame);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JComboBox clCombo;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JComboBox floorCombo;
    private javax.swing.JLabel imageLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLayeredPane layeredPane;
    private javax.swing.JList lightsStatusList;
    private javax.swing.JComboBox lsCombo;
    private javax.swing.JButton setButton;
    private javax.swing.JFrame setSingleLightFrame;
    private javax.swing.JLabel singleLightPercentLabel;
    private javax.swing.JScrollBar singleLightScrollbar;
    private javax.swing.JButton singleLightSetButton;
    private javax.swing.JLabel singleLightTitleLabel;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration//GEN-END:variables
}
